home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news!enno
- From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
- Newsgroups: comp.lang.c++
- Subject: Re: Copy constructing an already default constructed object
- Date: 26 Jan 1996 21:10:35 GMT
- Organization: Fachbereich Informatik, TH Darmstadt
- Distribution: world
- Message-ID: <ENNO.96Jan26221035@kitz.inferenzsysteme.informatik.th-darmstadt.de>
- References: <4e906b$stk@elaine32.Stanford.EDU>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- In-reply-to: brien@leland.Stanford.EDU's message of 25 Jan 1996 14:28:27 -0800
-
- In article <4e906b$stk@elaine32.Stanford.EDU> brien@leland.Stanford.EDU (brien oberstein) writes:
-
- I'd like to get some opinions on the best/cleanest way
- to accomplish the following:
-
- I've got an object which has already been constructed
- via its default constructor which just sets all pointers
- to NULL. Whats the best way to deep-copy into it?
-
-
- class A {
- public:
- A(); // default ctor
- A(const A&) // copy ctor
- A(const char *) // convert ctor
- };
-
- somefunc()
- {
- ...
- A a0;
- ...
- A a1("blah");
-
- //
- // How do you deep copy a1 into a0 ???
- //
- a0 = a1; // no good. shallow copy
- a0 = A(a1); // no good. dtor called for temp A object
- a0 = *new A(a1); // no good. creates memory for a A object
-
- //
- // the follow works but is tedious
- //
- A empty; // create an empty object
- A tmp(a1); // deep-copy a1 to temp
- a0 = tmp; // shallow-copy temp to a0
- tmp = empty; // clear out temp so internals are not destructed
-
- //
- // so overload = to make deep copies
- //
- a0 = a1;
-
- }
-
- //
- // deep-copy =
- //
- A& A::operator =(const A& other)
- {
- A empty;
- A tmp(other);
- memcpy(this, &tmp, sizeof(A));
- memcpy(&tmp, &empty, sizeof(A));
- return *this;
- }
-
-
- I'd like to know what people think of the solution I've reached.
- I figure that this type of shit is common enough so there should
- be some widely accepted solution to this problem. Or maybe its
- not, but believe me that the situation does occur.
-
- A class should define its copy-semantics, not the clients of that class.
- Often assignment can be expressed in terms of destruction and copy-
- construction, ie.
-
- Class& operator = (const Class& c) {
- if (this!=&c) {
- this->~Class(); // cleanup
- new (this) Class(c); // perform copy-construction
- }
- return *this;
- }
-
- In this case the constructor, destructor and copy-constructor are
- enough to determine the copy-semantics of the class. If a deep-copy
- is needed _you_ have to provide a suitable implementation for them.
- BTW performing a bitwise-copy using 'memcpy' is usually a bad idea.
-
- Enno
-